package com.wzx.data.serviceimpl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzx.basics.baseVo.Result;
import com.wzx.basics.exception.WzxException;
import com.wzx.basics.utils.ResultUtil;
import com.wzx.data.dao.mapper.SubjectMapper;
import com.wzx.data.entity.Course;
import com.wzx.data.entity.Permission;
import com.wzx.data.entity.Subject;
import com.wzx.data.listener.SubjectListener;
import com.wzx.data.service.ICourseService;
import com.wzx.data.service.ISubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzx.data.vo.SubjectEeVo;
import kotlin.jvm.internal.Lambda;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 科目表 服务层接口实现
 * @author wzx
 */
@Slf4j
@Service
public class ISubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements ISubjectService {

    @Autowired
    private SubjectListener subjectListener;
    @Autowired
    private ICourseService iCourseService;
    //课程分类列表
    //懒加载，每次查询一层数据
    @Override
    public List<Subject> selectSubjectList(String id) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Subject> subjectList = baseMapper.selectList(wrapper);
        //subjectList遍历，得到每个subject对象，判断是否有下一层数据，有hasChildren=true
        for (Subject subject:subjectList) {
            //获取subject的id值并查询
            boolean isChild = this.isChildren(subject.getId());
            //封装到对象里面
            subject.setHasChildren(isChild);
        }
        return subjectList;
    }

    //课程分类导出
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("科目分类", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            //查询课程分类表所有数据
            List<Subject> subjectList = baseMapper.selectList(null);
            List<SubjectEeVo> subjectEeVoList = new ArrayList<>();
            for (Subject subject: subjectList) {
                SubjectEeVo subjectEeVo = new SubjectEeVo();
                BeanUtils.copyProperties(subject,subjectEeVo);
                subjectEeVoList.add(subjectEeVo);
            }
            //EasyExcel写操作
            EasyExcel.write(response.getOutputStream(), SubjectEeVo.class)
                    .sheet("科目分类")
                    .doWrite(subjectEeVoList);
        }catch(Exception e) {
            throw new WzxException("导出失败");
        }
    }

    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),
                    SubjectEeVo.class,
                    subjectListener).sheet().doRead();
        } catch (IOException e) {
            throw new WzxException("导入失败");
        }
    }

    /**
     * 删除学科
     * @param id
     * @return
     */
    @Override
    @Transactional
    public void deleteSubject(String id) {
        //查询是否有子学科，若存在则不能删除
        LambdaQueryWrapper<Subject> sonLambda = new LambdaQueryWrapper<Subject>();
        sonLambda.eq(Subject::getParentId,id);
        Subject son = this.getOne(sonLambda);
        if(ObjectUtil.isNotNull(son)){
            throw new WzxException("该学科下有分支，不能删除");
        }
        //查询学科中是否存在课程，若存在则不能删除
        LambdaQueryWrapper<Course> courseLambda = new LambdaQueryWrapper<Course>();
        courseLambda.eq(Course::getSubjectId,id);
        Course course = iCourseService.getOne(courseLambda);
        if(ObjectUtil.isNotNull(course)){
            throw new WzxException("该学科下有课程，不能删除");
        }
        //删除学科
        this.removeById(id);
    }

    /**
     * 下载模板
     * @param response
     */
    @Override
    public void importTemplate(HttpServletResponse response) {
        try {
            //设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("科目分类", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            SubjectEeVo subjectEeVo = new SubjectEeVo();
            //EasyExcel写操作
            EasyExcel.write(response.getOutputStream(), SubjectEeVo.class)
                    .sheet("科目分类")
                    .doWrite((List) subjectEeVo);
        }catch(Exception e) {
            throw new WzxException("导出失败");
        }
    }

    @Override
    public List<Subject> getSubjectListByParentId(String id) {
        QueryWrapper<Subject> qw = new QueryWrapper<>();
        qw.eq("parent_id",id);
        qw.orderByAsc("sort");
        return this.list(qw);
    }

    private boolean isChildren(String subjectId) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",subjectId);
        Long count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}